# coding=utf-8
from locale import *
import sys
import datetime
from selenium import webdriver
from bs4 import BeautifulSoup


def get_mac_address():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac


def validate_mac_address():
    import urllib.request
    f = urllib.request.urlopen('http://amazon-ceping.xunhuanle.com/publicwelcome/getallmacaddress')
    ret_content_bytes = f.read()
    ret_content_str = ret_content_bytes.decode()
    return ret_content_str


def set_driver():
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    options.add_argument("--test-type")
    options.add_experimental_option('excludeSwitches', ['enable-automation'])

    prefs = {"profile.managed_default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)
    path = './chromedriver.exe'
    driver = webdriver.Chrome(executable_path=path, options=options)
    return driver


mac_address = get_mac_address()
print("Your macaddress is below:")
print(mac_address)
validation_content = validate_mac_address()
'''
if mac_address not in validation_content:
    print("Please submit your unicode '"+mac_address+"' to administrator!!!")
    sys.exit()
'''

file_name_output = "handler_link_"+datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')+".xls"

file_name_input = input("Input Will Import Link File Name:")
print("Import Link File Name is:", file_name_input)

runTimes = input("Run Times Every Cycle:")
runTimes = runTimes.strip()
run_times = int(runTimes)
print("Run Times Every Cycle is:", runTimes)

# 读取文件
setlocale(LC_NUMERIC, 'English_US')


driver = set_driver()
file = open(file_name_input, 'r')
i = 0
for line in file:
    i += 1
    url_list = line.split('\t')
    print(url_list)
    url = url_list[0]
    if url != 'Link':
        if i >= run_times:
            i = 0
            driver.quit()
            driver = set_driver()
        driver.get(url.strip())
        soup = BeautifulSoup(driver.page_source, "html.parser")
        form_twister = soup.select_one('#twister')
        if form_twister is None:
            print("NEED URL:"+url)
            file_output = open(file_name_output, 'a')
            file_output.writelines(line)
            file_output.close()
        else:
            print("NOT NEED URL:"+url)
file.close()
driver.quit()


